﻿
$(function () {
    // 初始化过滤器，该脚本需要放置于datagrid-filter.js之前
    if ($.fn.datagrid.defaults.operators) {
        $.fn.datagrid.defaults.operators.containsinarray = {
            text: 'Contains In Array',
            isMatch: function (source, value) {
                if (source.contains) {
                    return source.contains(value);
                }
                else {
                    return false;
                }
            }
        };
        $.fn.datagrid.defaults.operators.equalinarray = {
            text: 'Equal In Array',
            isMatch: function (source, value) {
                var matchResult = false;
                if (source
                    && source.length == 1
                    && source[0] == value) {
                    matchResult = true;
                }
                return matchResult;
            }
        };
        $.fn.datagrid.defaults.operators.notequalinarray = {
            text: 'Not Equal In Array',
            isMatch: function (source, value) {
                var matchResult = true;
                if (source
                    && source.length == 1
                    && source[0] == value) {
                    matchResult = false;
                }
                return matchResult;
            }
        };
        $.fn.datagrid.defaults.operators.exists = {
            text: 'Exists',
            isMatch: function (source, value) {
                var exists = false;
                if (source
                    && source.length >= 1) {
                    exists = true;
                }
                return (value == "有") ? exists : (!exists);
            }
        };
    }

    $.fn.datagrid.defaults.operators.nofilter.text = '清除筛选';
    $.fn.datagrid.defaults.operators.equal.text = '等于';
    $.fn.datagrid.defaults.operators.notequal.text = '不等于';

    $.fn.datagrid.defaults.operators.contains.text = '包含';
    $.fn.datagrid.defaults.operators.beginwith.text = '作为开头';
    $.fn.datagrid.defaults.operators.endwith.text = '作为结尾';

    $.fn.datagrid.defaults.operators.less.text = '小于';
    $.fn.datagrid.defaults.operators.lessorequal.text = '小于等于';
    $.fn.datagrid.defaults.operators.greater.text = '大于';
    $.fn.datagrid.defaults.operators.greaterorequal.text = '大于等于';

    $.fn.datagrid.defaults.operators.containsinarray.text = '包含';
    $.fn.datagrid.defaults.operators.equalinarray.text = '等于';
    $.fn.datagrid.defaults.operators.notequalinarray.text = '不等于';
    $.fn.datagrid.defaults.operators.exists.text = '存在';

    $.fn.datagrid.defaults.clearfilters = '清空所有自定义筛选条件';
    $.fn.datagrid.defaults.filterTips = '请输入查询条件';
});

var listGridHandler = function (inputData, binderName, jqGridID) {
    var me = this;
    var grid;
    var pageTotal = 0;
    var pageData = (inputData) ? inputData : {};
    var pageMetaData = (inputData) ? inputData.MetaData : {};
    var pageFilters;
    var isExporting = false;
    var isPrinting = false;
    var changeHandlers = {};

    // 对外接口
    this.iFrozenColumns = new Array();
    this.iHiddenColumns = new Array();

    // 加载成功事件，参数gridData（这个对象有两个属性：rows、total）
    this.iOnLoadSuccess = undefined;

    // 刪除成功后事件，参数node
    this.iOnDelete = undefined;


    // 添加Change事件，func参数：newValue, itemName, oldValue
    this.fAddChangeHandler = function (itemName, func) {
        if (amCommon.notEmpty(itemName) && typeof (func) == "function") {
            var itemHandlers = changeHandlers[itemName];
            if (!amCommon.isArray(itemHandlers)) {
                changeHandlers[itemName] = new Array();
                itemHandlers = changeHandlers[itemName];
            }

            itemHandlers.push(func);
        }
    };

    // 在分页工具栏添加按钮
    this.fAddPagerButtons = function (buttonList) {
        if (!amCommon.isArray(buttonList)) {
            return;
        }

        me.getPager().pagination({
            buttons: buttonList
        });
    };

    this.iDefaultFilters = new Array();

    // 每个对象有三个属性:field\op\value
    this.iForceFilters = new Array();
    this.iForceFilterString = undefined;

    // 可编辑View列表接口
    this.formID = undefined;
    this.formName = undefined;

    // 不可编辑Summary报表接口
    this.isSummary = false;

    this.isPwd = false;
    this.isStatus = false;
    this.lable = false; //标签生成
    this.Imagelable = false; //标签生成
    this.lableRemark = false; //标签生成记录
    this.jfRemark = false; //缴费记录
    this.proManage = false; //商品管理
    this.proManageX = false; //商品管理
    this.isZs = false;  //证书
    this.isEdit = true;
    this.proVote = false;  //产品调查
    this.lzRemark = false; //验证记录
    this.gxslzRemark = false;
    this.xjHbJL = false; //xianjinghongbao
    this.isDel = true;
    // 是否树表
    this.isTreeGrid = false;

    // 是否允许数据库中配置排序
    this.enableSort = true;
    this.filterParam = undefined;

    // 是否允许筛选
    this.enableFilter = true;

    this.fUpdateForceFilter = function (fieldName, fieldValue, operator) {
        for (var i = 0; i < me.iForceFilters.length; i++) {
            var filter = me.iForceFilters[i];
            if (filter.field == fieldName && (!operator || filter.op == operator)) {
                filter.value = fieldValue;
                return;
            }
        }

        // 若没有筛选项则加上
        if (fieldName && operator) {
            me.iForceFilters.push({
                field: fieldName,
                op: operator,
                value: fieldValue
            });
        }
    };

    this.fRemoveForceFilter = function (fieldName, operator) {
        for (var i = me.iForceFilters.length - 1; i >= 0; i--) {
            var filter = me.iForceFilters[i];
            if (filter.field == fieldName && (!operator || filter.op == operator)) {
                me.iForceFilters.splice(i, 1);
                return;
            }
        }
    };

    this.addGridOptions = function (optionsString) {
        var newOptions = $('#' + jqGridID).attr("data-options");
        if (newOptions && newOptions.trimEnd) {
            newOptions = newOptions.trimEnd(',') + ',';
        }
        newOptions = newOptions + optionsString;
        $('#' + jqGridID).attr("data-options", newOptions);
    };

    this.addColumnOptions = function (itemName, optionsString) {
        var column = $('#' + jqGridID).find('th[exField="' + itemName + '"]');
        var newOptions = column.attr("data-options");
        if (newOptions && newOptions.trimEnd) {
            newOptions = newOptions.trimEnd(',') + ',';
        }
        newOptions = newOptions + optionsString;
        column.attr("data-options", newOptions);
    };

    this.addColumnFormatter = function (itemName, formatterString) {
        me.addColumnOptions(itemName, 'formatter:' + formatterString);
    };

    this.invokeGrid = function (method, param) {

        if (me.isTreeGrid) {
            return me.grid.treegrid(method, param);
        }
        else {
            return me.grid.datagrid(method, param);
        }
    };

    this.getForceFilter = function (fieldName, operator) {
        var result = undefined;
        for (var i = 0; i < me.iForceFilters.length; i++) {
            var filter = me.iForceFilters[i];
            if (filter.field == fieldName && (!operator || filter.op == operator)) {
                result = filter.value;
                break;
            }
        }

        return result;
    }

    this.getFilter = function (fieldName) {
        var result = undefined;
        var rules = me.invokeGrid('options').filterRules;
        for (var i = 0; i < rules.length; i++) {
            if (rules[i].field == fieldName) {
                result = rules[i].value;
                break;
            }
        }
        return result;
    }

    this.getPanel = function () {
        return me.invokeGrid('getPanel');
    };

    this.getPager = function () {
        return me.invokeGrid('getPager');
    };

    this.getData = function () {
        return me.invokeGrid('getData');
    };

    this.getTotal = function () {
        return pageTotal;
    };

    this.getRow = function (index) {
        var rows = me.invokeGrid('getRows');
        return rows[index];
    };

    this.getEditUrl = function (recordID, taskID) {
        return '/Business/FormData/EditPage/' + recordID + '?FormID=' + me.formID + ((taskID) ? '&CurrentTaskID=' + taskID : '');
    };

    this.getViewUrl = function (recordID, taskID) {
        return '/Business/FormView/ViewPage/' + recordID + '?FormID=' + me.formID + ((taskID) ? '&CurrentTaskID=' + taskID : '');
    };

    this.getNewUrl = function () {
        return '/Business/FormData/NewPage?FormID=' + me.formID;
    };

    this.getMultiNewUrl = function () {
        return '/Business/MultiHandle/NewPage?FormID=' + me.formID;
    };

    this.getDeleteUrl = function (idString) {
        return "/api/FormData/Del/" + idString + "?FormID=" + me.formID;
    };
    this.getRecordPwd = function (idString) {

        return "/api/LBAdmin/RecordPwd/" + idString;
    };
    this.getZhenShu = function (idString) {

        return "/api/LBCert/CreateCert/" + idString + "?type=" + 1;
    };
    this.getStatus = function (idString, status) {

        return "/api/LBUser/SetStatus/" + idString + "?status=" + status;
    };
    this.GetLable = function (idString) {

        return "/User/LBProductLableSet/NewPageText/?parentid=" + idString;
    };
    this.GetImageLable = function (idString) {

        return "/User/LBProductLableSet/NewPage/?parentid=" + idString;
    };
    this.checkView = function (row) {
        return true;
    }
    this.Pwd = function (row) {
        return me.isPwd;
    }
    this.Status = function (row) {
        return me.isStatus;
    }
    this.Lable = function (row) {
        return me.lable;
    }
    this.ImageLable = function (row) {
        return me.Imagelable;
    }
    this.LableRemark = function (row) {
        return me.lableRemark;
    }
    this.JFRemark = function (row) {
        return me.jfRemark;
    }
    this.ProManage = function (row) {
        return me.proManage;
    }
    this.ProManageX = function (row) {
        return me.proManageX;
    }
    this.Zs = function (row) {
        return me.isZs;
    }
    this.checkEdit = function (row) {
        return me.isEdit;
    }
    this.ProVote = function (row) {
        return me.proVote;
    }
    this.LzRemark = function (row) {
        return me.lzRemark;
    }
    this.GxsLzRemark = function (row) {
        return me.gxslzRemark;
    }
    this.XjHbJL = function (row) {
        return me.xjHbJL;
    }
    this.checkDelete = function (row) {
        return me.isDel;
    }
    this.formatZSLink = function (value, row, index) {
        var result = '';
        if (me.Zs(row)) {
            if (me.checkEdit(row)) {
                result += '<a href="#" style="float:left" title="生成证书" onclick="' + binderName + '.CreateZS(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-zs"></div></a>';
            }
            else {
                result += '<a href="#" style="float:left;cursor:default" title="系统限制，无权生成证书"><div class="icon-page-view-disable"></div></a>';
            }
        }
        return result;
    }
    this.formatActionLink = function (value, row, index) {
        var result = '';
        //result=value;
        if (row && amCommon.notEmpty(row.id)) {
            if (me.getViewUrl) {
                if (me.checkView(row)) {
                    result += '<a href="#" style="float:left" title="查看" onclick="' + binderName + '.showViewDialog(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-view"></div></a>';
                }
                else {
                    result += '';// '<a href="#" style="float:left;cursor:default" title="系统限制，不允许查看"><div class="icon-page-view-disable"></div></a>';
                }
            }

            if (me.getEditUrl) {
                if (me.checkEdit(row)) {
                    result += '<a href="#" style="float:left" title="编辑" onclick="' + binderName + '.showEditDialog(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-edit"></div></a>';
                }
                else {
                    result += '';// '<a href="#" style="float:left;cursor:default" title="系统限制，不允许编辑"><div class="icon-page-edit-disable"></div></a>';
                }

            }
            if (me.Lable(row)) {
                if (me.checkEdit(row)) {
                    result += '<a href="#" style="float:left" title="标签生成设置" onclick="' + binderName + '.showsetLable(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-bq"></div></a>';

                }
                else {
                    result += '';//'<a href="#" style="float:left;cursor:default" title="系统限制，无权设置标签生成"><div class="icon-page-view-disable"></div></a>';
                }
            }

            if (me.ImageLable(row)) {
                if (me.checkEdit(row)) {

                    result += '<a href="#" style="float:left" title="图片标签生成" onclick="' + binderName + '.showsetImageLable(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-bq"></div></a>';
                }
                else {
                    result += '';//'<a href="#" style="float:left;cursor:default" title="系统限制，无权设置标签生成"><div class="icon-page-view-disable"></div></a>';
                }
            }
            if (me.ProVote(row)) {
                result += '<a href="#" style="float:left" title="产品调查" onclick="' + binderName + '.showProVote(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-cpdc"></div></a>';
            }
            if (me.LzRemark(row)) {
                result += '<a href="#" style="float:left" title="验证记录" onclick="' + binderName + '.showLzRemark(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-lzjl"></div></a>';
            }
            if (me.GxsLzRemark(row)) {
                result += '<a href="#" style="float:left" title="验证记录" onclick="' + binderName + '.showGxsLzRemark(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-lzjl"></div></a>';
            }
            if (me.XjHbJL(row)) {
                result += '<a href="#" style="float:left" title="红包记录" onclick="' + binderName + '.showXjHbJL(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-lzjl"></div></a>';
            }
            if (me.LableRemark(row)) {
                result += '<a href="#" style="float:left" title="下载防伪标签数据" onclick="' + binderName + '.showLableRemark(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-jldc"></div></a>';
            }
            if (me.JFRemark(row)) {
                result += '<a href="#" style="float:left" title="会员缴费记录" onclick="' + binderName + '.showJFRemark(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-jfjl"></div></a>';
            }
            if (me.ProManage(row)) {
                result += '<a href="#" style="float:left" title="会员商品列表" onclick="' + binderName + '.showProManage(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-splb"></div></a>';
            }
            if (me.ProManageX(row)) {
                result += '<a href="#" style="float:left" title="系列商品列表" onclick="' + binderName + '.showProManageX(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-splb"></div></a>';
            }
            if (me.Pwd(row)) {
                if (me.checkEdit(row)) {
                    result += '<a href="#" style="float:left" title="密码恢复" onclick="' + binderName + '.reductionPwd(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-pwd"></div></a>';
                }
                else {
                    result += '';// '<a href="#" style="float:left;cursor:default" title="系统限制，无权初始化密码"><div class="icon-page-view-disable"></div></a>';
                }
            }
            if (me.Status(row)) {
                if (me.checkEdit(row)) {

                    result += '<a href="#" style="float:left" title="状态设置" onclick="' + binderName + '.SetStatus(' + row._ID + ', ' + row.Status + ',' + row._TaskID + ', ' + index + ')"><div class="icon-page-zt"></div></a>';


                }
                else {
                    result += '';//'<a href="#" style="float:left;cursor:default" title="系统限制，无权更改状态"><div class="icon-page-view-disable"></div></a>';
                }
            }
            if (me.Zs(row)) {
                if (me.checkEdit(row)) {
                    result += '<a href="#" style="float:left" title="生成证书" onclick="' + binderName + '.CreateZS(' + row._ID + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-zs"></div></a>';
                }
                else {
                    result += '';//'<a href="#" style="float:left;cursor:default" title="系统限制，无权生成证书"><div class="icon-page-view-disable"></div></a>';
                }
            }
            if (me.getDeleteUrl) {
                if (me.checkDelete(row)) {
                    result += '<a href="#" style="float:left" title="删除" onclick="' + binderName + '.showDeleteDialog(' + row._ID + ')"><div class="icon-page-delete"></div></a>';
                }
                else {
                    result += '';// '<a href="#" style="float:left;cursor:default" title="系统限制，不允许删除"><div class="icon-page-delete-disable"></div></a>';
                }
            }
        } else {
            if (index == 0) {
                result = '统计方法:';
            } else if (index == 1) {
                result = '统计结果:';
            }
        }

        return result;
    };

    this.formatPictureLink = function (value, row, index) {
        var pictures = '';
        if (value && value.length > 0) {
            for (var i = 0; i < value.length; i++) {
                if (value[i].Path) {
                    var path = String.prototype.resolveClientUrl(value[i].Path);
                    var picLink = '<a style="float: left" title="点击查看附件" target="_blank" href="' + path + '"><div class="icon-picture-button"></div></a>';
                    pictures += picLink;
                }
            }
        }
        return pictures;
    };

    this.formatPercent = function (value) {
        if (value) {
            value = Number(value);
            var widthPercent = value;
            if (widthPercent < 0) {
                widthPercent = 0;
            }

            var percent = '<div style="width:' + widthPercent + '%;" class="grid-cell-percent">' + value + '%' + '</div>';
            return percent;
        } else {
            return '';
        }
    };

    this.formatDisplayName = function (value, row, index, itemName) {
        var result = value;

        if (row && amCommon.notEmpty(row._ID) && amCommon.notEmpty(itemName)) {
            if (amCommon.notEmpty(value) && !isNaN(value)) {
                result = '未绑定';//'已删(ID:' + value + ')';
            }

            var displayName = row['_DisplayName_' + itemName];
            if (amCommon.notEmpty(displayName)) {
                result = displayName;

                // 显示外键链接
                var metaData = pageMetaData[itemName];
                //if (metaData && metaData.DataTypeInfo == 'TypeSingleOneTableFK' && Number(value) > 0) {
                //    result = '<a href="#" onclick="' + binderName + '.showForeighKeyViewDialog(' + metaData.ForeignTableID + ', ' + value + ')">' + result + '</a>';
                //}
            }
        }

        return result;
    };
   ;
    this.formatProduct = function (value, row, index, itemName) {
        var result = value;

        if (value != "") {
            result = "<a href='#' onclick='window.showBusinessForm(\"查看商品\", \"/User/LBProduct/ViewPage/"+row[itemName]+"\")'>"+value+"</a>";
           

        } else {
            result = "";
        }



        return result;
    };
    this.formatStatus = function (value, row, index, itemName) {
        var result = value;

        if (value == 1) {
            result = "正常";
            if (row[itemName] == 0) {
                result += "(会员资料未完善)";
            } else if (row[itemName] == 1) {
                result += "(会员资料提交审核中)";
            } else if (row[itemName] == 2) {
                result += "(会员资料已驳回)";
            } else if (row[itemName] == 3) {
                result += "(会员资料已审核通过)";
            }

        } else {
            result = "未审核";
        }



        return result;
    };
    this.formatStatusG = function (value, row, index) {
        var result = value;

        if (value == 1) {
            result = "正常";
            

        } else if (value == 0) {
            result = "未审核";
        } else  {
            result = "锁定";
        }



        return result;
    };
    this.formatSHStatus = function (value, row, index) {
        var result = value;
        if (value == 1) {
            result = "已审核";
        } else {
            result = "未审核";
        }



        return result;
    };
    this.formatSendStatus = function (value, row, index) {
        var result = value;

        if (value == 1) {
            result = "已发放";
        } else {
            result = "未发放";
        }



        return result;
    };
    this.formatLevel = function (value, row, index) {
        var result = value;

        if (value == 1) {
            result = "优先";
        } else {
            result = "普通";
        }



        return result;
    };
    this.formatPJ = function (value, row, index) {
        var result = value;

        if (value == 1) {
            result = "一般";
        } else if (value == 2) {
            result = "好";
        } else if (value == 3) {
            result = "很好";
        }



        return result;
    };

    this.formatsex = function (value, row, index) {
        var result = value;

        if (value == 1) {
            result = "男";
        } else if (value == 0) {
            result = "女";
        }



        return result;
    };
    this.formatAction = function (value, row, index) {
        var result = value;

        if (value == 0) {
            result = "动态口令码验证";
        } else if (value == 1) {
            result = "电话查询验证";
        } else if (value == 3) {
            result = "微信验证";
        } else {
            result = "PC验证";
        }



        return result;
    };
    this.formatCount = function (value, row, index) {
        var result = value;

        if (value != undefined && value.length > 10) {
            result = "<span title='" + value + "'>" + value.subssubstr(0, 10) + "...</span>";
        }



        return result;
    };
    this.formatFunctionType = function (value, row, index) {
        var result = value;

        if (value == 1) {
            result = "上传产品数量";
        } else if (value == 2) {
            result = "生成标签数量";
        } else if (value == 3) {
            result = "查看产品验证记录";
        } else if (value == 4) {
            result = "查看消费者信息";
        }



        return result;
    };
    this.formatExport = function (value, row, index, itemName, AbitemName, Number) {
        var result = value;
        var status = row[itemName];

        var abpath = row[AbitemName];
        var number = row[Number];
        if (abpath != undefined) {
            if (status == 0) { result = "数据生成中(生成完毕需等待" + Math.ceil(number / 10000) + "分钟左右)..."; } else {

                if (abpath) {
                    result = "<a href='" + value + "'>防伪数据下载</a>";
                } else {
                    result = " 文件不存在.";
                }


            }
        }
        return result;
    };
    this.formatBoolean = function (value) {
        var result = '';
        if (value == true || value == "true") {
            result = '√';
        }
        return result;
    }

    this.showForeighKeyViewDialog = function (foreighKeyFormID, recordID) {
        window.exStopBubble();

        var url = '/Business/FormView/ViewPage/' + recordID + '?FormID=' + foreighKeyFormID;
        window.showBusinessForm(null, url);
    };

    this.addFilterOperator = function () {

    };

    function usageSingleSelection(jqGrid) {
        var exUsageType = jqGrid.attr('exUsageType');
        if (exUsageType == 'SingleSelection'
            || usageSingleReferCopy(jqGrid)
            || usageSingleListFilter(jqGrid)) {
            return true;
        }
        return false;
    }

    function usageSingleListFilter(jqGrid) {
        var exUsageType = jqGrid.attr('exUsageType');
        if (exUsageType == 'SingleListFilter') {
            return true;
        }
        return false;
    }

    function usageSingleReferCopy(jqGrid) {
        var exUsageType = jqGrid.attr('exUsageType');
        if (exUsageType == 'SingleReferCopy') {
            return true;
        }
        return false;
    }

    function usageMultiReferCopy(jqGrid) {
        var exUsageType = jqGrid.attr('exUsageType');
        if (exUsageType == 'MultiReferCopy') {
            return true;
        }
        return false;
    }

    function usageMultiSelection(jqGrid) {
        var exUsageType = jqGrid.attr('exUsageType');
        if (usageMultiReferCopy(jqGrid) || exUsageType == 'MultiSelection') {
            return true;
        }
        return false;
    }

    this.usageSelectionExceptFilter = function (jqGrid) {
        if (!usageSingleListFilter(jqGrid)
            && (usageSingleSelection(jqGrid) || usageMultiSelection(jqGrid))) {
            return true;
        }
        return false;
    }

    this.showEditDialog = function (recordID, taskID) {
        window.exStopBubble();

        if (me.getEditUrl) {
            if (!recordID) {
                var checkedRow = me.getCheckedRow();
                if (checkedRow) {
                    recordID = checkedRow._ID;
                    taskID = checkedRow._TaskID;
                }
                else {
                    return;
                }
            }

            window.showBusinessForm("编辑" + me.formName, me.getEditUrl(recordID, taskID));
        }
    };

    this.showViewDialog = function (recordID, taskID) {
        window.exStopBubble();

        if (me.getViewUrl) {
            if (!recordID) {
                var checkedRow = me.getCheckedRow();
                if (checkedRow) {
                    recordID = checkedRow._ID;
                    taskID = checkedRow._TaskID;
                }
                else {
                    return;
                }
            }

            window.showBusinessForm("查看" + me.formName, me.getViewUrl(recordID, taskID));
        }
    };

    this.showDeleteDialog = function (recordID) {
        window.exStopBubble();

        if (!me.getDeleteUrl) {
            return;
        }

        var idString = '';
        if (recordID > 0) {
            idString = recordID;
        }
        else {
            var checkedRows = me.invokeGrid('getSelections');
            if (!checkedRows || checkedRows.length <= 0) {
                $.messager.alert('提示', "请选择需要删除的记录！", 'info');
                return;
            }

            for (var i = 0; i < checkedRows.length; i++) {
                if (checkedRows[i].SystemIsSystem) {
                    $.messager.alert('提示', "很抱歉，您没有权限删除所选的记录！", 'info');
                    return;
                }
                idString += checkedRows[i]._ID + ',';
            }
        }

        $.messager.confirm('删除确认', '确实要删除选中的记录？', function (r) {
            if (r) {
                $.ajax({
                    type: "POST",
                    url: me.getDeleteUrl(idString)
                })
                .success(function (result) {
                    if (result > 0) {
                        me.refreshGrid();
                        if (me.iOnDelete) {
                            me.iOnDelete();
                        }
                    }
                    else if (result == -2) {
                        $.messager.alert('提示', "有其他资料引用该数据，禁止删除！", "error");
                    }
                    else {

                        $.messager.alert('提示', "有其他资料引用该数据，禁止删除！", "error");
                    }
                })
                .error(function (result) {
                    var message = "很抱歉，操作出现异常！请联系管理员。";
                    if (result) {
                        if (result.responseJSON && result.responseJSON.ExceptionMessage) {
                            message = result.responseJSON.ExceptionMessage;
                        }
                        else if (result.responseText) {
                            message = result.responseText;
                        }
                    }

                    $.messager.alert('错误', message.replace("-10", ""), 'error');
                });
            }
        });
    };

    this.reductionPwd = function (recordID) {

        if (!me.getRecordPwd) {
            return;
        }

        var idString = '';
        if (recordID > 0) {
            idString = recordID;
        }
        else {
            var checkedRows = me.invokeGrid('getSelections');
            if (!checkedRows || checkedRows.length <= 0) {
                $.messager.alert('提示', "请选择需要初始化密码的记录！", 'info');
                return;
            }

            for (var i = 0; i < checkedRows.length; i++) {

                idString += checkedRows[i]._ID + ',';
            }
        }

        $.ajax({
            type: "POST",
            url: me.getRecordPwd(idString)
        })
                .success(function (result) {
                    if (result > 0) {
                        $.messager.alert('提示', "你好，密码已经初始化为‘123456’", 'info');
                        me.refreshGrid();

                    }
                })
                .error(function (result) {
                    var message = "很抱歉，操作出现异常！请联系管理员。";
                    if (result) {
                        if (result.responseJSON && result.responseJSON.ExceptionMessage) {
                            message = result.responseJSON.ExceptionMessage;
                        }
                        else if (result.responseText) {
                            message = result.responseText;
                        }
                    }

                    $.messager.alert('错误', message, 'error');
                });
    };


    this.showsetLable = function (recordID, taskID) {
        window.exStopBubble();

        if (me.GetLable) {
            if (!recordID) {
                var checkedRow = me.getCheckedRow();
                if (checkedRow) {
                    recordID = checkedRow._ID;
                    taskID = checkedRow._TaskID;
                }
                else {
                    return;
                }
            }

            window.showBusinessForm("标签生成设置", me.GetLable(recordID));
        }
    };
    this.showsetImageLable = function (recordID, taskID) {
        window.exStopBubble();

        if (me.GetImageLable) {
            if (!recordID) {
                var checkedRow = me.getCheckedRow();
                if (checkedRow) {
                    recordID = checkedRow._ID;
                    taskID = checkedRow._TaskID;
                }
                else {
                    return;
                }
            }

            window.showBusinessForm("标签生成设置", me.GetImageLable(recordID));
        }
    };
    this.showProVote = function (recordID, taskID) {
        window.parent.window.MenuClickHrefEvent("/User/LBProductLable/Index?proid=" + recordID, "产品调查", "tabsChildContent_1");
    }; 
    this.showLzRemark = function (recordID, taskID) {
        window.parent.window.MenuClickHrefEvent("/User/LBProductValidate/Index?labid=" + recordID, "验证记录", "tabsChildContent_1");
    };
    this.showGxsLzRemark = function (recordID, taskID) {
        window.parent.window.MenuClickHrefEvent("/User/LBProductValidate/GxsIndex?labid=" + recordID, "验证记录", "tabsChildContent_1");
    };
    this.showXjHbJL = function (recordID) {
        window.parent.window.MenuClickHrefEvent("/User/LBXjHb/JLIndex?userid=" + recordID, "红包记录", "tabsChildContent_1");
    };
    this.showLableRemark = function (recordID, taskID) {
        window.parent.window.MenuClickHrefEvent("/User/LBProductLableSet/Export?proid=" + recordID, "记录导出", "tabsChildContent_1");
    };
    this.showJFRemark = function (recordID, taskID) {
        window.parent.window.MenuClickHrefEvent("/Admin/LBUserPaymentRecord/Index?userid=" + recordID, "缴费记录", "tabsChildContent_1");
    };
    this.showProManage = function (recordID, taskID) {
        window.parent.window.MenuClickHrefEvent("/User/LBProduct/index?userid=" + recordID, "商品管理", "tabsChildContent_1");
    };
    this.showProManageX = function (recordID, taskID) {
        window.parent.window.MenuClickHrefEvent("/User/LBProduct/index?XlID=" + recordID, "商品管理", "tabsChildContent_1");
    };
    this.CreateZS = function (recordID) {

        if (!me.getZhenShu) {
            return;
        }

        var idString = '';
        if (recordID > 0) {
            idString = recordID;
        }
        else {
            var checkedRows = me.invokeGrid('getSelections');
            if (!checkedRows || checkedRows.length <= 0) {

                return;
            }

            for (var i = 0; i < checkedRows.length; i++) {

                idString += checkedRows[i]._ID + ',';
            }
        }


        $.ajax({
            type: "POST",
            url: me.getZhenShu(idString)
        })
                      .success(function (result) {
                          if (result) {
                              $("#MyZsValue").attr("zs", result);
                              $("#MyZsValue").val(result);
                              $.messager.alert('提示', "你好，加密狗数据生成成功,请导出到加密狗", 'info');

                          } else {
                              $.messager.alert('错误', "你好，请检查加密狗是否插好", 'error');
                          }
                      })
                      .error(function (result) {
                          var message = "很抱歉，操作出现异常！请联系管理员。";
                          if (result) {
                              if (result.responseJSON && result.responseJSON.ExceptionMessage) {
                                  message = result.responseJSON.ExceptionMessage;
                              }
                              else if (result.responseText) {
                                  message = result.responseText;
                              }
                          }

                          $.messager.alert('错误', message, 'error');
                      });



    };
    this.SetStatus = function (recordID, status) {

        if (!me.getStatus) {
            return;
        }

        var idString = '';
        if (recordID > 0) {
            idString = recordID;
        }
        else {
            var checkedRows = me.invokeGrid('getSelections');
            if (!checkedRows || checkedRows.length <= 0) {

                return;
            }

            for (var i = 0; i < checkedRows.length; i++) {

                idString += checkedRows[i]._ID + ',';
            }
        }


        $.ajax({
            type: "POST",
            url: me.getStatus(idString, status)
        })
                      .success(function (result) {
                          if (result) {
                              me.refreshGrid();
                              $.messager.alert('提示', "你好，状态设置成功", 'info');

                          } else {
                              $.messager.alert('错误', "你好，状态设置失败，请重试", 'error');
                          }
                      })
                      .error(function (result) {
                          var message = "很抱歉，操作出现异常！请联系管理员。";
                          if (result) {
                              if (result.responseJSON && result.responseJSON.ExceptionMessage) {
                                  message = result.responseJSON.ExceptionMessage;
                              }
                              else if (result.responseText) {
                                  message = result.responseText;
                              }
                          }

                          $.messager.alert('错误', message, 'error');
                      });



    };

    this.showReferDialog = function (referedTableID, referedTableName) {
        var newLayer = window.showBusinessDialog(referedTableID, referedTableName, null, null, null, 'SingleReferCopy');
        newLayer.showNewDialogByRefer = function (selectedRow) {
            // 关闭选择引用记录的对话框
            top.closeDialog();

            // 弹出以引用方式新建的对话框
            if (selectedRow && selectedRow._ID > 0 && me.getNewUrl) {
                var referUrl = me.getNewUrl() + '&ReferedTableID=' + referedTableID + '&ReferedRecordID=' + selectedRow._ID;
                window.showBusinessForm("新建" + me.formName, referUrl);
            }
        };
    };

    this.showCopyDialog = function () {
        var copyRecordID = getCheckedRecordID();
        if (copyRecordID > 0 && me.getNewUrl) {
            var copyUrl = me.getNewUrl() + '&ReferedRecordID=' + copyRecordID;
            window.showBusinessForm("新建" + me.formName, copyUrl);
        }
    };

    this.showNewDialog = function () {
        if (me.getNewUrl) {
            window.showBusinessForm("新建" + me.formName, me.getNewUrl());
        }
    };

    this.showMultiNewDialog = function () {
        if (me.getMultiNewUrl) {
            window.showBusinessForm("批量新建" + me.formName, me.getMultiNewUrl());
        }
    };

    this.refreshGrid = function () {
        if (me.grid) {
            me.invokeGrid('reload');
        }
    };

    this.bindComboClear = function (element) {
        if (element == undefined) {
            element = this;
        }

        var comboClear = new comboClearFunction(element);
        comboClear.addClearButton();
    };

    this.getCheckedRow = function () {
        var checkedRows = me.invokeGrid('getChecked');
        if (!checkedRows || checkedRows.length <= 0) {
            $.messager.alert('提示', "请选择一行记录！", 'info');
            return null;
        }

        if (checkedRows.length > 1) {
            $.messager.alert('提示', "请选择一行记录，当前选择的行数过多！", 'info');
            return null;
        }

        return checkedRows[0];
    }

    function getCheckedRecordID() {
        var checkedRow = me.getCheckedRow();
        return (checkedRow ? checkedRow._ID : -1);
    }

    function onComboChange(element, value, filterOperator) {
        var item = null;
        if (element.className == 'tree') {
            item = $(element).tree('options').exItemName;
        }
        else {
            item = $(element).combo('options').exItemName;
        }

        if (element.exComboClear && element.exComboClear.showClearButton) {
            element.exComboClear.showClearButton(value);
        }

        if (item) {
            if (value == undefined || value == null || value.toString().length <= 0) {
                me.invokeGrid('removeFilterRule', item);
            } else {
                me.invokeGrid('addFilterRule', {
                    field: item,
                    op: filterOperator,
                    value: value
                });
            }
            me.invokeGrid('doFilter');
        }
    }

    function createComboField(itemName, filterOperator, controlType, dataType) {
        var field =
        {
            field: itemName,
            type: (controlType) ? controlType : 'combobox',
            options: {
                exItemName: itemName,
                editable: false,
                onSelect: function (record) {
                    var recordValue;
                    if (record) {
                        recordValue = record.value;
                    }
                    else {
                        recordValue = $(this).combo('getValue');
                    }
                    onComboChange(this, recordValue, filterOperator);
                },
                onChange: function (newValue, oldValue) {
                    if (newValue == undefined || newValue == null || newValue.toString().length <= 0) {
                        onComboChange(this, null, filterOperator);
                    }

                    if (dataType == 'TypeSingleOneTableFK'
                        || dataType == 'TypeSerialNumberCreationFK'
                        || dataType == 'TypeSerialNumberSelectionFK') {
                        me.bindChangeEvents(newValue, oldValue, $(this).combo('options').exItemName);
                    }
                }
            }
        };

        return field;
    }

    function createComboTreeField(itemName, filterOperator) {
        var field =
        {
            field: itemName,
            type: 'combotree',
            options: {
                exItemName: itemName,
                editable: true,
                url: '/api/AuthorityDepartment/List?IsSelect=1',
                onChange: function (newValue, oldValue) {
                    onComboChange(this, newValue, filterOperator);
                },
                onInit: function () { me.bindComboClear(this); }
            }
        };

        return field;
    }

    function updateParentSelectValue(oneceSelectedRows, isUnSelect, keepPopupWindow, allSelectedRows) {
        if (top.getLastLayer) {
            var lastLayer = top.getLastLayer();
            if (lastLayer && lastLayer.updatePopupSelectValue) {
                lastLayer.updatePopupSelectValue(oneceSelectedRows, isUnSelect, keepPopupWindow, allSelectedRows, pageFilters);
            }
        }
    }

    function parentShowNewDialogByRefer(selectedRow) {
        if (top.getLastLayer) {
            var lastLayer = top.getLastLayer();
            if (lastLayer && lastLayer.showNewDialogByRefer) {
                lastLayer.showNewDialogByRefer(selectedRow);
            }
        }
    }

    function isSingleSelect() {
        var singleSelect = (me.grid.attr('exSingleSelect') == "true");
        var singleSelection = usageSingleSelection(me.grid);
        var multiSelection = usageMultiSelection(me.grid);

        if (multiSelection) {
            singleSelect = false;
        }

        if (singleSelection) {
            singleSelect = true;
        }

        return singleSelect;
    }

    function bindGridEvent() {
        var options = me.invokeGrid('options');
        var singleSelection = usageSingleSelection(me.grid);
        var multiSelection = usageMultiSelection(me.grid);
        if (multiSelection) {
            me.onSelectMultiSelection = function (rowIndex, rowData) {
                updateParentSelectValue([rowData], null, true);
            };

            me.onSelectAllMultiSelection = function (rows) {
                updateParentSelectValue(rows, null, true);
            };

            options.onUnselect = function (rowIndex, rowData) {
                updateParentSelectValue([rowData], true, true);
            };

            options.onUnselectAll = function (rows) {
                updateParentSelectValue(rows, true, true);
            };

            options.onLoadSuccess = function (data) {
                if (!data || !data.rows) {
                    return;
                }

                // 标识选中行
                $.each(data.rows, function (index, item) {
                    if (item._CheckRow == true) {
                        me.invokeGrid('checkRow', index);
                    }
                });
            }
        }

        if (singleSelection || multiSelection) {

            if (usageSingleReferCopy(me.grid)) {
                options.onDblClickRow = function (rowIndex, rowData) {
                    parentShowNewDialogByRefer(rowData)
                };
            }
            else {
                options.onDblClickRow = function (rowIndex, rowData) {
                    updateParentSelectValue([rowData], null, null, [rowData]);
                };
            }
        }
    }

    this.saveParentSelectValue = function () {
        var selectedRows = me.invokeGrid('getSelections');
        updateParentSelectValue(null, null, null, selectedRows);
    }

    this.rejectParentSelectValue = function () {
        if (top.getLastLayer) {
            var lastLayer = top.getLastLayer();
            if (lastLayer && lastLayer.rejectSelectValue) {
                lastLayer.rejectSelectValue();
            }
        }
    }

    this.eventBeforeLoad = function (param) {
        pageFilters = undefined;
        if (!param) {
            return true;
        }

        // 加入上游传入的强制筛选参数
        param.exSelectIDs = pageData.SelectIDs;
        var forceFilterArray = me.iForceFilters.concat();
        if (amCommon.notEmpty(pageData.FilterItemName) && pageData.FilterItemValue > 0) {
            forceFilterArray.push({
                field: pageData.FilterItemName,
                op: 'equal',
                value: pageData.FilterItemValue
            });
        }

        // 初始加载时加入各页自定义默认筛选条件
        if (me.iDefaultFilters && me.iDefaultFilters.length > 0) {
            param.filterRules = me.grid.datagrid('options').filterStringify(me.iDefaultFilters);
            me.iDefaultFilters = new Array();
        }

        // 加入各页自定义的强制筛选统计
        var addFilters = (amCommon.notEmpty(me.iForceFilterString) ? (me.iForceFilterString + ',') : '');
        if (forceFilterArray && forceFilterArray.length > 0) {
            var forceFilters = me.grid.datagrid('options').filterStringify(forceFilterArray);
            if (amCommon.notEmpty(forceFilters)) {
                forceFilters = forceFilters.toString().trim('[').trim(']');
                if (amCommon.notEmpty(forceFilters)) {
                    addFilters += forceFilters + ',';
                }
            }
        }

        // 加入系统定义的强制筛选统计
        if (me.usageSelectionExceptFilter(me.grid)) {
            addFilters += amCommon.business.selectionFilter();
        }

        // 拼接筛选统计
        addFilters = addFilters.trimEnd(',');
        if (amCommon.notEmpty(addFilters)) {
            pageFilters = addFilters;
            if (!amCommon.notEmpty(param.filterRules)) {
                param.filterRules = '[' + addFilters + ']';
            }
            else {
                var orignalFilters = param.filterRules.toString().trim('[').trim(']');
                if (!amCommon.notEmpty(orignalFilters)) {
                    param.filterRules = '[' + addFilters + ']';
                } else {
                    pageFilters = orignalFilters + ',' + addFilters;
                    param.filterRules = '[' + pageFilters + ']';
                }
            }
        }

        me.filterParam = param;
    };

    this.eventLoadSuccess = function (gridData) {

        // 解决Grid无数据时不显示横向滚动条的问题
        if (!gridData || !(gridData.rows) || gridData.rows.length <= 0) {
            var width = me.grid.prev(".datagrid-view2").find(".datagrid-header-row").width();

            if (width > 0) {
                me.grid.prev(".datagrid-view2").children(".datagrid-body").html("<div style='width:" + width + "px;border:solid 0px;height:15px;color:gray'>当前没有数据。</div>");
            }
        }

        if (me.iOnLoadSuccess && typeof (me.iOnLoadSuccess) == "function") {
            me.iOnLoadSuccess(gridData);
        }

        if (gridData && gridData.total >= 0) {
            pageTotal = gridData.total;
        } else {
            pageTotal = 0;
        }
    };

    this.eventLoadError = function (result) {

        var message = "很抱歉，操作出现异常！请联系管理员。";
        if (result) {
            if (result.responseJSON && result.responseJSON.ExceptionMessage) {
                message = result.responseJSON.ExceptionMessage;
            }
            else if (result.responseText) {
                message = result.responseText;
            }
        }

        document.write(message);
    };

    this.eventSelectAll = function (rows) {
        if (me.onSelectAllMultiSelection) {
            me.onSelectAllMultiSelection(rows);
        }

        if (me.onSelectAllHandle) {
            me.onSelectAllHandle(rows);
        }
    };

    this.onSelectAllMultiSelection = undefined;

    this.onSelectAllHandle = function (rows) {
        if (rows) {
            for (var index = 0; index < rows.length; index++) {
                if (!me.checkDelete(rows[index])) {
                    me.grid.datagrid("uncheckRow", index);
                    me.grid.datagrid("unselectRow", index);
                }
            }
        }
    };

    this.eventSelect = function (rowIndex, rowData) {
        if (me.onSelectMultiSelection) {
            me.onSelectMultiSelection(rowIndex, rowData);
        }

        if (me.onSelectHandle) {
            me.onSelectHandle(rowIndex, rowData);
        }
    };

    this.onSelectMultiSelection = undefined;

    this.onSelectHandle = function (rowIndex, rowData) {
        if (!me.checkDelete(rowData)) {
            me.grid.datagrid("uncheckRow", rowIndex);
            me.grid.datagrid("unselectRow", rowIndex);
        }
    };

    this.bindChangeEvents = function (newValue, oldValue, itemName) {
        // 执行额外绑定的Change事件处理程序
        if (newValue != oldValue) {
            var itemHandlers = changeHandlers[itemName];
            if (itemHandlers && amCommon.isArray(itemHandlers)) {
                $.each(itemHandlers, function (index, func) {
                    if (typeof (func) == "function") {
                        func(newValue, itemName, oldValue);
                    }
                });
            }
        }
    };

    this.bindFilter = function () {
        me.grid = $('#' + jqGridID);
        me.addFilterOperator();

        var filterFields = [];
        for (var itemName in pageMetaData) {

            var field = {
                field: itemName,
                type: 'validatebox',
                op: ['contains', 'equal', 'notequal', 'beginwith', 'endwith']
            };

            var metaData = pageMetaData[itemName];

            switch (metaData.DataTypeInfo) {
                default:
                case 'TypeSinglelineText':
                case 'TypeMultilineText':
                    break;

                case 'TypeSingleSelect':
                case 'TypeFlowState':
                    field = createComboField(itemName, 'equal');
                    field.options.editable = true;
                    field.options.data = metaData.EnumValues;
                    field.options.onInit = function () { me.bindComboClear(this); };
                    break;

                case 'TypeMultiSelect':
                    field = createComboField(itemName, 'containsinarray');
                    field.options.editable = true;
                    field.options.data = metaData.EnumValues;
                    field.options.onInit = function () { me.bindComboClear(this); };
                    break;

                case 'TypeDatetime':
                    field = {
                        field: itemName,
                        type: 'datebox',
                        op: ['equal', 'notequal', 'greater', 'greaterorequal', 'less', 'lessorequal'],
                        options: { editable: false }
                    };
                    break;

                case 'TypeBoolean':
                    field = createComboField(itemName, 'equal');
                    field.options.data = [{ 'value': '1', 'text': '是' }, { 'value': '0', 'text': '否' }];
                    field.options.onInit = function () { me.bindComboClear(this); };
                    break;

                case 'TypeInteger':
                    field = {
                        field: itemName,
                        type: 'numberbox',
                        op: ['equal', 'notequal', 'greater', 'greaterorequal', 'less', 'lessorequal']
                    };
                    break;

                case 'TypeDecimal':
                    field = {
                        field: itemName,
                        type: 'numberbox',
                        options: { precision: metaData.DecimalLength },
                        op: ['equal', 'notequal', 'greater', 'greaterorequal', 'less', 'lessorequal']
                    };
                    break;

                case 'TypeSingleDepartment':
                    field = createComboTreeField(itemName, 'equal');
                    break;

                case 'TypeMultiDepartment':
                    field = createComboTreeField(itemName, 'containsinarray');
                    break;

                case 'TypeSingleUser':
                    field = createComboField(itemName, 'equal');
                    field.options.editable = true;
                    field.options.onInit = function () {
                        me.bindComboClear(this);
                        var comboTextButton = new comboTextButtonFunction(this);
                        comboTextButton.addTextButton();

                        var comboAutoComplete = new comboAutoCompleteFunction(this, this.exComboClear);
                        comboAutoComplete.userAutoComplete();
                    };
                    break;

                case 'TypeMultiUser':
                    field = createComboField(itemName, 'containsinarray');
                    field.options.editable = true;
                    field.options.onInit = function () {
                        me.bindComboClear(this);
                        var comboTextButton = new comboTextButtonFunction(this);
                        comboTextButton.addTextButton();

                        var comboAutoComplete = new comboAutoCompleteFunction(this, this.exComboClear);
                        comboAutoComplete.userAutoComplete();
                    };
                    break;

                case 'TypeMultiPicture':
                case 'TypeMultiAttachment':
                    field = createComboField(itemName, 'exists');
                    field.options.onInit = function () { me.bindComboClear(this); };
                    field.options.data = [{ 'value': '1', 'text': '有' }, { 'value': '0', 'text': '无' }];
                    break;

                case 'TypeSingleOneTableFK':
                case 'TypeSerialNumberCreationFK':
                case 'TypeSerialNumberSelectionFK':
                    field = createComboField(itemName, 'containsinarray', 'combobox', metaData.DataTypeInfo);
                    field.options.editable = true;
                    field.options.foreignTableUrl = metaData.ForeignTableUrl;
                    field.options.foreignTableApi = metaData.foreignTableApi;
                    field.options.onInit = function () {
                        me.bindComboClear(this);

                        var elementOptions = $(this).combo('options');
                        var item = elementOptions.exItemName;
                        var itemMeta = pageMetaData[item];
                        elementOptions.exUsageListFilter = true;
                        elementOptions.foreignTableUrl = itemMeta.ForeignTableUrl;
                        elementOptions.foreignTableApi = itemMeta.ForeignTableApi;

                        var comboPopupSelect = new comboPopupSelectFunction(this,
                            itemMeta.ForeignTableID, '', itemMeta.ForeignTextItemName);
                        comboPopupSelect.addPopupSelect();

                        var comboAutoComplete = new comboAutoCompleteFunction(this, this.exComboClear);
                        comboAutoComplete.foreignKeyAutoComplete(itemMeta.ForeignTableID, itemMeta.ForeignTextItemName);
                    };
                    break;
            }

            filterFields.push(field);
        }

        var frozenFieldContainer = me.grid.find('thead[data-options="frozen:true"] tr');

        if (me.enableSort) {
            // 列排序 // mark 需要改进性能
            var fieldList = new Array();
            var frozenFieldList = new Array();
            var fieldContainer = me.grid.find('thead[data-options!="frozen:true"] tr');
            for (var itemName in pageMetaData) {
                var findField = fieldContainer.find('th[exField="' + itemName + '"]');
                if (findField.length > 0) {
                    if (me.iFrozenColumns && me.iFrozenColumns.contains(itemName)) {
                        frozenFieldList.push(findField);
                    }
                    else {
                        fieldList.push(findField);
                    }

                    if (pageMetaData[itemName].Filterable == false) {
                        var newOptions = findField.attr("data-options");
                        if (newOptions && newOptions.trimEnd) {
                            newOptions = newOptions.trimEnd(',') + ',';
                        }
                        newOptions = newOptions + 'filterable:false';
                        findField.attr("data-options", newOptions);
                    }
                }
            }

            if (frozenFieldList.length > 0) {
                frozenFieldContainer.append(frozenFieldList);
            }

            fieldContainer.empty();
            fieldContainer.append(fieldList);
        }

        // 设置CheckBox列
        if (isSingleSelect()) {
            frozenFieldContainer.find('th[exField="_CheckRow"]').remove();
        }

        // 隐藏列
        if (me.iHiddenColumns && me.iHiddenColumns.length > 0) {
            for (var i = 0; i < me.iHiddenColumns.length; i++) {
                var hiddenColumn = me.iHiddenColumns[i];
                fieldContainer.find('th[exField="' + hiddenColumn + '"]').remove();
                frozenFieldContainer.find('th[exField="' + hiddenColumn + '"]').remove();
            }
        }

        var defaultFilterRules = me.iDefaultFilters;
        me.invokeGrid({
            onBeforeLoad: me.eventBeforeLoad,
            onLoadSuccess: me.eventLoadSuccess,
            onLoadError: me.eventLoadError,
            onSelectAll: me.eventSelectAll,
            onSelect: me.eventSelect
        });
        bindGridEvent();

        // 筛选条件
        if (me.enableFilter) {
            me.invokeGrid('enableFilter', filterFields);
            if (defaultFilterRules && defaultFilterRules.length > 0) {
                for (var i = 0; i < defaultFilterRules.length; i++) {
                    var filterRule = defaultFilterRules[i];
                    if (filterRule) {
                        me.invokeGrid('addFilterRule', filterRule);
                    }
                }
            }
        }

        var url = me.grid.attr('exUrl');
        if (url) {
            me.invokeGrid('options').url = url;
        }
    }

    this.importData = function () {
        window.showDialog(me.formName + "导入", "/Business/Attachment/ImportPage?FormID=" + me.formID, 400, 300);
    };

    this.exportData = function () {
        if (!isExporting) {
            isExporting = true;

            var url = "/api/ImportExport/ExportData?FormID=" + me.formID;
            if (me.isSummary) {
                url = "/api/ImportExport/ExportReport?FormID=" + me.formID;
            }

            $.ajax({
                type: "POST",
                url: url,
                data: me.filterParam
            })
            .success(function (result) {
                if (result == 'false') {
                    $.messager.alert('提示', "很抱歉，操作出现异常！请联系管理员。", "error");
                }
                else {
                    var address = window.location;
                    window.open(address.protocol + '//' + address.host + result);
                }
                isExporting = false;
            })
            .error(function (result) {
                isExporting = false;
                $.messager.alert('提示', result.responseText, "error");
            });
        }
        else {
            $.messager.alert('提示', '正在导出文件...请稍等！', 'info');
        }
    };

    this.printData = function () {
        if (!isPrinting) {
            var copyRecordID = getCheckedRecordID();
            isPrinting = true;
            if (copyRecordID > 0) {
                var url = "/api/ImportExport/ExportTemplate?FormID=" + me.formID + "&recordID=" + copyRecordID + "&isSummary=" + me.isSummary + "&templateID=-1";

                $.ajax({
                    type: "POST",
                    url: url
                })
                .success(function (result) {
                    if (result == 'false') {
                        $.messager.alert('提示', "很抱歉，操作出现异常！请联系管理员。", "error");
                    }
                    else {
                        var address = window.location;
                        window.open(address.protocol + '//' + address.host + result);
                    }
                    isPrinting = false;
                })
                .error(function (result) {
                    isPrinting = false;
                    $.messager.alert('提示', result.responseText, "error");
                });
            }
            else {
                isPrinting = false;
            }
        }
        else {
            $.messager.alert('提示', '正在打印文件...请稍等！', 'info');
        }
    };
}